package javbot.command;

import java.awt.AWTException;
import java.awt.MouseInfo;

public class CmdGoTo extends Command{

	final int x;
	final int y;
	final int delay;
	final int iteration;
		
	public CmdGoTo(int x,int y) throws AWTException {
		super();
		this.x = x;
		this.y = y;
		delay = 6;
		iteration = 3;
	}
	
	public void execute() {
		
		
		int startx = MouseInfo.getPointerInfo().getLocation().x;
		int starty = MouseInfo.getPointerInfo().getLocation().y;
		double gradient = ((double) (y - starty)) / ((double) (x - startx));
		double intercept = starty - (gradient * startx);
		
		boolean moveL2R = false;
		boolean moveD2U = false;
		boolean iterateAlongX = false;
		if (x == startx && y == starty) 
			return; // already there
		else if (Math.abs(gradient) <= 1) {
			moveL2R = startx < x;
			iterateAlongX = true;
		}
		else {
			moveD2U = starty < y;		
		}
		
//			System.out.println("Target: (" + x + "," + y + ")");
//			System.out.println("Start: (" + startx + "," + starty + ")");		
//			System.out.println("Gradient: " + gradient);
//			System.out.println("Intercept: " + intercept);

		int newX = startx;
		int newY = starty;
		
		if (iterateAlongX) {
			while (true) {
				if (moveL2R) newX += iteration; else newX -= iteration;
				if ((moveL2R && newX >= x) || ((!moveL2R) && newX <= x)) break;
				newY = (int) (newX*gradient + intercept);			
				robotMove(newX, newY);
			}
		} else {
			while (true) {
				if (moveD2U) newY += iteration; else newY -= iteration;
				if (((moveD2U && newY >= y) || (!moveD2U) && newY <= y)) break;
				newX = (int) ((newY - intercept)/gradient);			
				robotMove(newX, newY);
			}
		}
		
		if (newX != x || newY != y) {
			robot.mouseMove(x,y);
		}
	}

	private void robotMove(int newX, int newY) {
		//			System.out.println("Move to (" + newX + "," + newY + ")");
					robot.mouseMove(newX,newY);			
					robot.delay(delay);
	}	

	public String toString() {
		return "Go to (" + x + "," + y + ")";
	}	
	
}
